package com.wechat.wins.http;

import java.util.HashMap;
import java.util.Map;

import com.wechat.wins.util.XMLParse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsServerHandler extends ChannelInboundHandlerAdapter {
    private final Logger logger = LoggerFactory.getLogger(HttpsServerHandler.class);

    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        this.logger.info(msg.toString());
        if (msg instanceof FullHttpRequest) {
            final FullHttpRequest request = (FullHttpRequest) msg;
            final boolean keepAlive = HttpUtil.isKeepAlive(request);
            final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            final String url = request.uri();
            this.logger.info("request URL: {}", url);
            if (url.startsWith("/wechatMP")) {

                final String[] paramStr = url.substring(url.indexOf('?')+1).split("&");
                final Map<String, String> params = convertParams(paramStr);
                final String signature = params.get("signature");
                final String timestamp = params.get("timestamp");
                final String nonce = params.get("nonce");
                final String echostr = params.get("echostr");

                if (request.method() == HttpMethod.GET) {
                    if (checkSignature(signature, timestamp, nonce)) {
                        response.content().writeBytes(echostr.getBytes());
                    }
                    this.logger.info(params.toString());
                } else if (request.method() == HttpMethod.POST) {
//                    XMLParse.extract(msg);
                    ByteBuf content = request.content();
                    logger.info(content.toString(CharsetUtil.UTF_8));
                    String respMsg = XMLParse.generate("hello", signature, timestamp, nonce);
                    logger.info(respMsg);
                    response.content().writeBytes(respMsg.getBytes());
                }
            } else {
                response.content().writeBytes("Hello".getBytes());
            }


            response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
            response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
            if (keepAlive) {
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.writeAndFlush(response);
            } else {
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }

    private Map<String, String> convertParams(final String[] paramStr) {
        final Map<String, String> res = new HashMap<>();
        String[] kv;
        for (final String str : paramStr) {
            kv = str.split("=");
            res.put(kv[0], kv[1]);
        }
        return res;
    }

    public boolean checkSignature(final String signature, final String timestamp, final String nonce) {
        return true;
    }
}
